import React, { useEffect, useState } from "react";
import { InfiniteScroll, PullToRefresh, List, Avatar, Switch, DotLoading, Toast } from "antd-mobile";
import styles from './index.module.less'
import { EyeFill, EditSOutline, DeleteOutline, AddOutline, ExclamationCircleOutline } from 'antd-mobile-icons'
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { getPersonChatList, handleSetDefaultRole, deleteRole } = $globalServicer('chat')

const RoleItem = (props) => {
  const { tabType } = props;
  const PageSize = 10; // 每页加载的数据条数
  const [page, setPage] = useState(1); // 当前页码
  const [listData, setListData] = useState([]); // 列表数据
  const [hasMore, setHasMore] = useState(false); // 是否有更多数据
  const [refreshing, setRefreshing] = useState(false); // 刷新状态
  const [loading, setLoading] = useState(false); // 加载状态
  const [operating, setOperating] = useState(false); // 添加操作锁状态
  const customNavigate = $globalNavigate()

  // 加载更多数据的逻辑
  const fetchListData = async () => {
    setLoading(true); // 设置加载状态为 true
    const newData = await getPersonChatList();
    // const currentRolesImg = newData.filter(item => item.persona_type === 1)[0]
    // const defaultRoleImg = localStorage.getItem('default_cover')
    // if (currentRolesImg.cover !== defaultRoleImg) {
    //   localStorage.setItem('default_cover', currentRolesImg.cover)
    // }
    setListData([{
      persona_name: '',
      description: '',
      avatar: '',
      id: -1,
    }, ...newData]); // 累加新数据
    setLoading(false); // 结束加载状态
  };
  const InfiniteScrollContent = ({ loading }) => {
    return (
      <>
        {loading ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 已到达底部 ---</span>
        )}
      </>
    )
  }
  // 首次加载数据
  useEffect(() => {
    fetchListData(); // 加载新分类的数据
  }, []);
  // 下拉刷新逻辑
  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchListData(); // 重新加载第一页的数据
    setRefreshing(false);
  };
  // 统一的接口处理函数
  const handleOperation = async (operation, successMsg) => {
    if (operating) {
      showErrorToast('请等待当前操作完成');
      return;
    }

    try {
      setOperating(true); // 开始操作，加锁
      Toast.show({
        icon: 'loading',
        content: '处理中...',
        duration: 0,
      });

      await operation(); // 执行操作

      showSuccessToast(successMsg);
      
      await fetchListData(); // 刷新列表
    } catch (error) {
      showErrorToast(error.message || '操作失败');
    } finally {
      setOperating(false); // 操作完成，解锁
    }
  };
  // 删除角色
  const handleDeleteRole = async (id) => {
    handleOperation(
      async () => {
        await deleteRole({ id });
      },
      '删除成功'
    );
  };
  // 设置默认角色
  const setDefaultRole = async (item) => {
    if (item.persona_type === 1) {
      showSuccessToast('至少保留一个默认角色');
      return;
    }

    handleOperation(
      async () => {
        await handleSetDefaultRole({ id: item.id });
        handleSetSessionItem('childReloads', true);
      },
      '设置成功'
    );
  };
  const handleSetSessionItem = (key, value) => {
    sessionStorage.setItem(key, value);
    const parentWindow = window;
    parentWindow.sessionStorage.setItem(key, value);
    // parentWindow.reloadPage();
    // window.parent.jg_reload()
  }
  return (
    <div>
      <PullToRefresh
        // key={itemKey}
        onRefresh={handleRefresh}
        refreshing={refreshing}
      >
        <div className={styles.roleList}>
          <List>
            {listData.length > 0 && listData.map((item, index) => (
              <List.Item key={index}>
                {
                  item.id !== -1 ? <div className={styles.roleItem}>
                    <div className={styles.roleItemTop}>
                      <Avatar src={item.cover} />
                      {/* <div className={styles.roleItemTopRight}>
                        <Switch
                          style={{
                            '--checked-color': 'var(--adm-color-primary)',
                          }}
                          checked={item.persona_type === 1}
                          onChange={async () => await setDefaultRole(item)}
                          disabled={operating} // 操作中禁用开关
                        />
                      </div> */}
                    </div>
                    <div className={styles.roleItemContent}>
                      <p className={styles.roleItemTitle}>
                        {
                          item.persona_name
                        }
                      </p>
                      <p className={styles.roleItemDesc}>
                        {item.remarks}
                      </p>
                      {/* <p className={styles.roleItemRemarks}><ExclamationCircleOutline fontSize={12} color="#989898" />&nbsp;{item.remarks.length ? item.remarks : '暂无备注信息'}</p> */}
                    </div>
                    <div className={styles.roleItemFooter}>
                      <EditSOutline 
                        onClick={() => {
                          if (operating) return; // 操作中禁止编辑
                          if (item.chats.length > 0) {
                            showErrorToast('您已使用该角色开始故事无法修改');
                            return;
                          }
                          customNavigate(`/chatRole/details?type=edit&id=${item.id}&tabType=${tabType}`);
                        }} 
                      />
                      <DeleteOutline 
                        onClick={() => {
                          if (operating) return; // 操作中禁止删除
                          if (item.chats.length > 0) {
                            showErrorToast('您已使用该角色开始故事无法删除');
                            return;
                          }
                          handleDeleteRole(item.id)
                        }}
                        style={{ opacity: operating ? 0.5 : 1 }} // 操作中显示禁用状态
                      />
                    </div>
                  </div> : <div className={styles.roleItemAddWrapper} onClick={() => {
                    if (operating) return; // 操作中禁止添加
                    customNavigate(`/chatRole/details?&type=add&tabType=${tabType}`);
                  }} >
                    <div className={styles.roleItemAdd}>
                      <div className={styles.roleItemAddIcon}>
                        <AddOutline color={getComputedStyle(document.documentElement).getPropertyValue('--theme-border-secondary').trim()} size={24} />
                      </div>
                      <p>点击添加新角色</p>
                    </div>
                  </div>
                }
              </List.Item>
            ))}
          </List>
        </div>
        <InfiniteScroll threshold={20} >
          <InfiniteScrollContent loading={loading} />
        </InfiniteScroll>
      </PullToRefresh>
    </div>
  );
};

export default RoleItem;
